<template>
  <div class="goods-returns-create">
    <el-page-header
      :content="pageTitle"
      @back="handleBack"
      class="page-header"
    />

    <el-form
      ref="formRef"
      :model="goodsReturnsForm"
      :rules="formRules"
      label-width="110px"
      class="returns-form"
      :disabled="isDetailMode"
    >
      <el-card shadow="never" class="card-section">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
            <el-tag v-if="goodsReturnsForm.goodsReturnsStatusText" size="small">
              {{ goodsReturnsForm.goodsReturnsStatusText }}
            </el-tag>
          </div>
        </template>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item prop="goodsReturnsNo">
              <template #label>
                <span>退货单号</span>
              </template>
              <el-input
                v-model="goodsReturnsForm.goodsReturnsNo"
                placeholder="自动获取系统编号"
                readonly
                class="readonly-input"
              >
                <template #append v-if="!isDetailMode">
                  <el-button
                    :loading="generatingCode"
                    @click="generateReturnsCode"
                  >
                    自动生成
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="goodsReturnsDate">
              <el-date-picker
                v-model="goodsReturnsForm.goodsReturnsDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择退货日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="进货单号" prop="stockinGoodsNo">
              <el-input
                v-model="goodsReturnsForm.stockinGoodsNo"
                placeholder="请选择"
                readonly
                @click="openStockinDialog"
              >
                <template #suffix v-if="!isDetailMode">
                  <el-button link type="primary" @click.stop="openStockinDialog">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-input
                v-model="goodsReturnsForm.supplierName"
                placeholder="请选择进货单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsContact"
                placeholder="请选择进货单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsContactPhone"
                placeholder="请选择进货单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="进货部门">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsDepartment"
                placeholder="请选择进货单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="进货人">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsUser"
                placeholder="请选择进货单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退货原因">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsReason"
                placeholder="请输入退货原因"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核人">
              <el-input
                v-model="goodsReturnsForm.goodsReturnsAuditor"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核时间">
              <el-input v-model="goodsReturnsForm.createrTime" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="goodsReturnsForm.goodsReturnsRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-card>

      <el-card shadow="never" class="card-section">
        <template #header>
          <div class="card-header detail-header">
            <span>退货明细</span>
            <div class="detail-actions" v-if="!isDetailMode">
              <el-button type="primary" @click="openGoodsDialog">
                添加
              </el-button>
              <el-button
                type="danger"
                plain
                :disabled="!selectedDetailRows.length"
                @click="removeSelectedDetails"
              >
                移除
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          ref="detailTableRef"
          :data="goodsReturnDetails"
          border
          style="width: 100%"
          empty-text="请先选择进货单并通过“添加”按钮选择货品"
          @selection-change="handleDetailSelectionChange"
        >
          <el-table-column v-if="!isDetailMode" type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="productName" label="货品名称" min-width="140" />
          <el-table-column prop="productCode" label="货品编号" min-width="140" />
          <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
          <el-table-column prop="specification" label="规格型号" min-width="120" />
          <el-table-column prop="unitName" label="单位" width="80" />
          <el-table-column prop="stockinQuantity" label="进货数量" width="100" />
          <el-table-column prop="storedQuantity" label="已入库" width="90" />
          <el-table-column prop="unstoredQuantity" label="未入库" width="90" />
          <el-table-column label="* 本次退货数量" width="140">
            <template #default="{ row }">
              <el-input-number
                v-model="row.returnQuantity"
                :precision="0"
                :min="0"
                :max="Math.max(row.unstoredQuantity ?? 0, 0)"
                :disabled="isDetailMode"
                controls-position="right"
                placeholder="必填"
                @change="updateRowAmount(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="退货单价" width="140">
            <template #default="{ row }">
              <el-input-number
                v-model="row.unitPrice"
                :precision="2"
                :min="0"
                controls-position="right"
                :disabled="isDetailMode"
                @change="updateRowAmount(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="退货金额" width="140">
            <template #default="{ row }">
              ¥{{ row.returnAmount?.toFixed(2) || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                placeholder="请输入"
                :disabled="isDetailMode"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isDetailMode"
            label="操作"
            width="80"
            fixed="right"
          >
            <template #default="scope">
              <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="detail-summary" v-if="goodsReturnDetails.length">
          <span>退货种类：<strong>{{ detailSummary.kinds }}</strong></span>
          <span>退货数量：<strong>{{ detailSummary.count }}</strong></span>
          <span>退货金额：<strong>¥{{ detailSummary.amount.toFixed(2) }}</strong></span>
        </div>
      </el-card>
    </el-form>

    <div class="fixed-footer" v-if="!isDetailMode">
      <div class="footer-actions">
        <el-button @click="handleBack">关闭</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave()">
          保存
        </el-button>
        <el-button
          type="success"
          :loading="saving"
          @click="handleSave('new')"
        >
          保存并新增
        </el-button>
      </div>
    </div>

    <!-- 选择进货单 -->
    <el-dialog
      v-model="stockinDialogVisible"
      title="选择进货单"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="stockinSearchForm" :inline="true" class="search-form">
        <el-form-item label="进货单号">
          <el-input
            v-model="stockinSearchForm.stockinGoodsNo"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input
            v-model="stockinSearchForm.supplierName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="进货部门">
          <el-input
            v-model="stockinSearchForm.organizationName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="进货人">
          <el-input
            v-model="stockinSearchForm.userName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="stockinSearchForm.stockinGoodsStatusList"
            multiple
            collapse-tags
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="option in STOCKIN_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进货日期">
          <el-date-picker
            v-model="stockinSearchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchStockinList">查询</el-button>
          <el-button @click="resetStockinSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="stockinTableLoading"
        :data="stockinTableData"
        highlight-current-row
        @row-click="handleStockinRowClick"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="选择" width="70">
          <template #default="{ row }">
            <el-radio v-model="selectedStockinId" :label="row.stockinGoodsId">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
          <el-table-column prop="stockinGoodsNo" label="进货单号" min-width="160" />
        <el-table-column label="单据状态" width="110">
          <template #default="{ row }">
            <el-tag
              :type="getStockinStatusTag(row.stockinGoodsStatus)"
              size="small"
            >
              {{ row.stockinGoodsStatusText || getStockinStatusText(row.stockinGoodsStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="stockinGoodsDate" label="进货日期" width="130">
          <template #default="{ row }">
            {{ formatDate(row.stockinGoodsDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" min-width="160" />
        <el-table-column prop="organizationName" label="进货部门" width="140" />
        <el-table-column prop="userName" label="进货人" width="100" />
        <el-table-column prop="stockinGoodsCount" label="货品数量" width="100" />
        <el-table-column prop="stockinGoodsAmount" label="进货金额" width="140">
          <template #default="{ row }">
            ¥{{ Number(row.stockinGoodsAmount ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="stockinPagination.pageindex"
          v-model:page-size="stockinPagination.pagesize"
          :total="stockinPagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleStockinSizeChange"
          @current-change="handleStockinPageChange"
        />
      </div>

      <template #footer>
        <el-button @click="stockinDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!selectedStockinRow"
          @click="confirmStockinSelection"
        >
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加退货明细 -->
    <el-dialog
      v-model="goodsDialogVisible"
      title="添加货品"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="goods-dialog-header" v-if="selectedStockinRow">
        <div>退货单号：{{ goodsReturnsForm.goodsReturnsNo || '待生成' }}</div>
        <div>进货单号：{{ selectedStockinRow?.stockinGoodsNo }}</div>
        <div>进货日期：{{ formatDate(selectedStockinRow?.stockinGoodsDate) }}</div>
      </div>

      <el-table
        v-loading="goodsDialogLoading"
        :data="stockinGoodsDetailList"
        @selection-change="handleGoodsSelectionChange"
        height="420"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" min-width="140" />
        <el-table-column prop="productCode" label="货品编号" min-width="140" />
        <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="stockinQuantity" label="进货数量" width="100" />
        <el-table-column prop="storedQuantity" label="已入库" width="90" />
        <el-table-column prop="unstoredQuantity" label="未入库" width="90" />
        <el-table-column prop="unitPrice" label="进货单价" width="120">
          <template #default="{ row }">
            ¥{{ Number(row.unitPrice ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!selectedGoodsRows.length"
          @click="confirmGoodsSelection"
        >
          确认添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

interface GoodsReturnsForm {
  goodsReturnsId?: string | number
  goodsReturnsNo: string
  goodsReturnsDate: string
  stockinGoodsId: string | number | null
  stockinGoodsNo: string
  supplierId?: string | number
  supplierName?: string
  goodsReturnsContact?: string
  goodsReturnsContactPhone?: string
  goodsReturnsDepartment?: string
  goodsReturnsUser?: string
  goodsReturnsReason?: string
  goodsReturnsRemark?: string
  goodsReturnsAuditor?: string
  createrTime?: string
  goodsReturnsStatus?: number
  goodsReturnsStatusText?: string
}

interface GoodsReturnDetailRow {
  uid: string
  stockinGoodsDetailId?: string | number
  productId?: string | number
  productName?: string
  productCode?: string
  productTypeName?: string
  specification?: string
  unitName?: string
  stockinQuantity?: number
  storedQuantity?: number
  unstoredQuantity?: number
  returnQuantity: number
  unitPrice?: number
  returnAmount: number
  remark?: string
}

interface StockinGoodsItem {
  stockinGoodsId: string | number
  stockinGoodsNo: string
  stockinGoodsStatus?: number
  stockinGoodsStatusText?: string
  stockinGoodsDate?: string
  supplierId?: string | number
  supplierName?: string
  stockinContact?: string
  stockinContactPhone?: string
  organizationId?: string | number
  organizationName?: string
  userId?: string | number
  userName?: string
  stockinGoodsCount?: number
  stockinGoodsAmount?: number
}

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()

const goodsReturnsForm = reactive<GoodsReturnsForm>({
  goodsReturnsNo: '',
  goodsReturnsDate: moment().format('YYYY-MM-DD'),
  stockinGoodsId: null,
  stockinGoodsNo: '',
  supplierName: '',
  goodsReturnsContact: '',
  goodsReturnsContactPhone: '',
  goodsReturnsDepartment: '',
  goodsReturnsUser: '',
  goodsReturnsReason: '',
  goodsReturnsRemark: '',
  goodsReturnsAuditor: '',
  createrTime: '',
})

const goodsReturnDetails = ref<GoodsReturnDetailRow[]>([])
const selectedDetailRows = ref<GoodsReturnDetailRow[]>([])

const generatingCode = ref(false)
const saving = ref(false)

const ALLOWED_STOCKIN_STATUS = [3, 4]

const STOCKIN_STATUS_OPTIONS = [
  { label: '草稿', value: 0, tagType: 'info' },
  { label: '待审核', value: 1, tagType: 'warning' },
  { label: '驳回', value: 2, tagType: 'danger' },
  { label: '未出库', value: 3, tagType: 'info' },
  { label: '部分出库', value: 4, tagType: 'warning' },
  { label: '已完成', value: 5, tagType: 'success' },
  { label: '已关闭', value: 6, tagType: 'danger' },
]

const stockinDialogVisible = ref(false)
const stockinSearchForm = reactive({
  stockinGoodsNo: '',
  supplierName: '',
  organizationName: '',
  userName: '',
  stockinGoodsStatusList: [...ALLOWED_STOCKIN_STATUS],
  dateRange: [] as string[],
})
const stockinTableLoading = ref(false)
const stockinTableData = ref<StockinGoodsItem[]>([])
const stockinPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0,
})
const selectedStockinId = ref<string | number | null>(null)
const selectedStockinRow = ref<StockinGoodsItem | null>(null)

const goodsDialogVisible = ref(false)
const goodsDialogLoading = ref(false)
const stockinGoodsDetailList = ref<GoodsReturnDetailRow[]>([])
const selectedGoodsRows = ref<GoodsReturnDetailRow[]>([])

const pageMode = ref((route.query.mode as string) || 'create')
const editingId = ref(route.query.goodsReturnsId ? String(route.query.goodsReturnsId) : '')
const isDetailMode = computed(() => pageMode.value === 'detail')
const isEditMode = computed(() => !!editingId.value && !isDetailMode.value)
const pageTitle = computed(() => {
  if (isDetailMode.value) return '退货详情'
  if (isEditMode.value) return '编辑退货单'
  return '新增退货单'
})

const formRules: FormRules = {
  goodsReturnsNo: [{ required: true, message: '退货单号不能为空', trigger: 'blur' }],
  goodsReturnsDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
  stockinGoodsNo: [{ required: true, message: '请选择进货单号', trigger: 'change' }],
}

const detailSummary = reactive({
  kinds: 0,
  count: 0,
  amount: 0,
})

const formatDate = (value?: string | null) => {
  if (!value) return ''
  return moment(value).format('YYYY-MM-DD')
}

const updateSummary = () => {
  const rows = goodsReturnDetails.value
  detailSummary.kinds = rows.length
  detailSummary.count = rows.reduce((sum, row) => sum + Number(row.returnQuantity || 0), 0)
  detailSummary.amount = rows.reduce((sum, row) => sum + Number(row.returnAmount || 0), 0)
}

const updateRowAmount = (row: GoodsReturnDetailRow) => {
  const qty = Number(row.returnQuantity || 0)
  const price = Number(row.unitPrice || 0)
  row.returnAmount = Number((qty * price).toFixed(2))
  updateSummary()
}

const getStockinStatusOption = (status: number | string | undefined) => {
  if (status === undefined || status === null) return undefined
  const statusNumber = Number(status)
  return STOCKIN_STATUS_OPTIONS.find((item) => Number(item.value) === statusNumber)
}

const getStockinStatusText = (status: number | string | undefined) => {
  return getStockinStatusOption(status)?.label || '未知'
}

const getStockinStatusTag = (status: number | string | undefined) => {
  return getStockinStatusOption(status)?.tagType || 'info'
}

watch(
  () => goodsReturnDetails.value.length,
  () => updateSummary(),
)

const handleDetailSelectionChange = (rows: GoodsReturnDetailRow[]) => {
  selectedDetailRows.value = rows
}

const removeSelectedDetails = () => {
  if (!selectedDetailRows.value.length) return
  goodsReturnDetails.value = goodsReturnDetails.value.filter(
    (item) => !selectedDetailRows.value.includes(item),
  )
  selectedDetailRows.value = []
  updateSummary()
}

const removeDetail = (index: number) => {
  goodsReturnDetails.value.splice(index, 1)
  updateSummary()
}

const NUMBER_RULE_TARGET_CODE = 'GoodsReturns'
const NUMBER_RULE_DEFAULT_NAME = '退货'
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (num: number, len = 2) => `${num}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((item: string) => item.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY':
          return String(now.getFullYear())
        case 'YY':
          return String(now.getFullYear()).slice(-2)
        case 'MM':
          return pad(now.getMonth() + 1)
        case 'DD':
          return pad(now.getDate())
        case 'HH':
          return pad(now.getHours())
        case 'MI':
          return pad(now.getMinutes())
        case 'SS':
          return pad(now.getSeconds())
        default:
          return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const resolveNumberRule = (rules: any[]) => {
  if (!Array.isArray(rules) || !rules.length) return null
  return (
    rules.find((rule) => rule?.targetCode === NUMBER_RULE_TARGET_CODE) ||
    rules.find((rule) => rule?.targetName?.includes(NUMBER_RULE_DEFAULT_NAME)) ||
    rules[0]
  )
}

const fetchNumberRule = async () => {
  const tryFetch = async (params?: Record<string, any>) => {
    const res = await myaxios.get('/api/Number/QueryNumberingRules', {
      params,
    })
    if (res?.data?.code !== 200) return []
    return Array.isArray(res?.data?.data) ? res.data.data : []
  }

  let rule: any | null = null
  try {
    const list = await tryFetch({
      targetCode: NUMBER_RULE_TARGET_CODE,
      targetName: NUMBER_RULE_DEFAULT_NAME,
    })
    rule = resolveNumberRule(list)
  } catch (err) {
    console.warn('QueryNumberingRules 带过滤条件失败，尝试无条件加载', err)
  }

  if (!rule) {
    const list = await tryFetch()
    rule = resolveNumberRule(list)
  }

  if (!rule) {
    throw new Error('未配置退货单编号规则，请先在“编号规则”中添加')
  }
  return rule
}

const requestReturnsCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: NUMBER_RULE_TARGET_CODE, targetName: NUMBER_RULE_DEFAULT_NAME },
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '编号服务不可用')
  } catch (error) {
    console.warn('GenerateNumber 接口不可用，尝试编号规则 fallback', error)
    const rule = await fetchNumberRule()
    return buildCodeFromRule(rule)
  }
}

const generateReturnsCode = async () => {
  if (generatingCode.value) return
  generatingCode.value = true
  try {
    goodsReturnsForm.goodsReturnsNo = await requestReturnsCode()
    ElMessage.success('退货单号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成退货单号失败')
  } finally {
    generatingCode.value = false
  }
}

const initAuditorInfo = async () => {
  try {
    const res = await myaxios.get('/api/User/GetMyProfile')
    const data = res?.data?.data || {}
    const name =
      data.userName ||
      data.realName ||
      data.nickname ||
      localStorage.getItem('username') ||
      ''
    if (name) {
      goodsReturnsForm.goodsReturnsAuditor = name
      localStorage.setItem('username', name)
    }
  } catch (error) {
    const cache = localStorage.getItem('username') || ''
    goodsReturnsForm.goodsReturnsAuditor = cache
  } finally {
    goodsReturnsForm.createrTime = moment().format('YYYY-MM-DD HH:mm:ss')
  }
}

const openStockinDialog = () => {
  if (isDetailMode.value) return
  stockinDialogVisible.value = true
  fetchStockinList()
}

const resetStockinSearch = () => {
  stockinSearchForm.stockinGoodsNo = ''
  stockinSearchForm.supplierName = ''
  stockinSearchForm.organizationName = ''
  stockinSearchForm.userName = ''
  stockinSearchForm.stockinGoodsStatusList = [...ALLOWED_STOCKIN_STATUS]
  stockinSearchForm.dateRange = []
  fetchStockinList()
}

const fetchStockinList = async () => {
  stockinTableLoading.value = true
  try {
    const res = await myaxios.get('/api/StockinGoods/GetStockinGoods', {
      params: {
        stockinGoodsNo: stockinSearchForm.stockinGoodsNo,
        supplierName: stockinSearchForm.supplierName,
        organizationName: stockinSearchForm.organizationName,
        userName: stockinSearchForm.userName,
        stockinGoodsStatus:
          stockinSearchForm.stockinGoodsStatusList?.length
            ? stockinSearchForm.stockinGoodsStatusList.join(',')
            : ALLOWED_STOCKIN_STATUS.join(','),
        beginDate: stockinSearchForm.dateRange?.[0] || '',
        endDate: stockinSearchForm.dateRange?.[1] || '',
        pageindex: stockinPagination.pageindex,
        pagesize: stockinPagination.pagesize,
      },
    })
    if (res?.data?.code === 200) {
      const list = res?.data?.data?.data || res?.data?.data || []
      stockinTableData.value = list.filter((item: StockinGoodsItem) =>
        ALLOWED_STOCKIN_STATUS.includes(Number(item?.stockinGoodsStatus ?? item?.stockinGoodsStatus ?? 0)),
      )
      stockinPagination.total = res?.data?.data?.listCount ?? res?.data?.data?.total ?? stockinTableData.value.length
    }
  } catch (error) {
    console.error('获取进货单失败', error)
  } finally {
    stockinTableLoading.value = false
  }
}

const handleStockinSizeChange = (size: number) => {
  stockinPagination.pagesize = size
  fetchStockinList()
}

const handleStockinPageChange = (page: number) => {
  stockinPagination.pageindex = page
  fetchStockinList()
}

const handleStockinRowClick = (row: StockinGoodsItem) => {
  selectedStockinId.value = row.stockinGoodsId
  selectedStockinRow.value = row
}

const applyStockinToForm = (row: StockinGoodsItem) => {
  selectedStockinRow.value = row
  goodsReturnsForm.stockinGoodsId = row.stockinGoodsId
  goodsReturnsForm.stockinGoodsNo = row.stockinGoodsNo
  goodsReturnsForm.supplierId = row.supplierId
  goodsReturnsForm.supplierName = row.supplierName
  goodsReturnsForm.goodsReturnsContact = row.stockinContact
  goodsReturnsForm.goodsReturnsContactPhone = row.stockinContactPhone
  goodsReturnsForm.goodsReturnsDepartment = row.organizationName
  goodsReturnsForm.goodsReturnsUser = row.userName
}

const requestStockinDetail = async (url: string, stockinGoodsId: string | number) => {
  return myaxios.get(url, { params: { stockinGoodsId } })
}

const detailFieldCandidates = [
  'goodsDetails',
  'details',
  'stockinGoodsDetails',
  'StockinGoodsDetails',
  'stockinGoodsDetailList',
  'stockinGoodsDetail',
  'detailList',
  'detailLists',
  'items',
  'data',
  'list',
  'records',
  'rows',
  'result',
  '',
]

const toArraySafe = (value: any): any[] => {
  if (!value && value !== 0) return []
  if (Array.isArray(value)) return value
  if (typeof value === 'string') {
    try {
      const trimmed = value.trim()
      if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
        const parsed = JSON.parse(trimmed)
        return Array.isArray(parsed) ? parsed : []
      }
      return []
    } catch {
      return []
    }
  }
  if (typeof value === 'object') {
    if (value instanceof Map || value instanceof Set) {
      return Array.from(value as Iterable<any>)
    }
    const cascadeKeys = ['data', 'list', 'records', 'items', 'rows']
    for (const key of cascadeKeys) {
      const inner = (value as any)?.[key]
      if (Array.isArray(inner)) return inner
    }
    return Object.values(value)
  }
  return []
}

const resolveDetailList = (res: any): any[] => {
  const containers = [res?.data?.data, res?.data, res]
  for (const container of containers) {
    if (!container) continue
    for (const key of detailFieldCandidates) {
      const segment = key ? container?.[key] : container
      const array = toArraySafe(segment)
      if (array.length) return array
    }
  }
  return []
}

const loadStockinGoodsDetail = async (stockinGoodsId: string | number) => {
  goodsDialogLoading.value = true
  const candidates = [
    '/api/StockinGoods/GetStockinGoodsDetail',
    '/api/StockinGoods/GetStockingoodsDetail',
  ]
  for (const url of candidates) {
    try {
      const res = await requestStockinDetail(url, stockinGoodsId)
      const detailList = resolveDetailList(res)
      if (!detailList.length) {
        console.warn('进货明细接口返回为空，尝试下一个', url, res?.data)
        continue
      }
      stockinGoodsDetailList.value = detailList
        .filter((item: any) => !!item)
        .map((item: any, index: number) => ({
          uid: `${item?.stockinGoodsDetailId || item?.productId || index}`,
          stockinGoodsDetailId: item?.stockinGoodsDetailId || item?.Id || item?.stockinGoodsDetailID,
          productId: item?.productId ?? item?.ProductId ?? null,
          productName: item?.productName ?? item?.ProductName ?? '',
          productCode: item?.productCode ?? item?.ProductCode ?? '',
          productTypeName: item?.productTypeName ?? item?.ProductTypeName ?? '',
          specification:
            item?.productSpecification ||
            item?.specification ||
            item?.Specification ||
            item?.specificationModel ||
            '',
          unitName: item?.unit || item?.productUnit || item?.unitName || '',
          stockinQuantity: Number(
            item?.quantity ??
              item?.stockinQuantity ??
              item?.currentInventory ??
              item?.purchaseQuantity ??
              0,
          ),
          storedQuantity: Number(item?.storedQuantity || item?.inQuantity || 0),
          unstoredQuantity: Number(
            item?.unstoredQuantity ??
              item?.pendingQuantity ??
              Number(
                item?.quantity ??
                  item?.stockinQuantity ??
                  item?.currentInventory ??
                  item?.purchaseQuantity ??
                  0,
              ) - Number(item?.storedQuantity || 0),
          ),
          unitPrice: Number(
            item?.unitPrice ?? item?.purchasePrice ?? item?.price ?? item?.amount ?? 0,
          ),
          returnQuantity: 0,
          returnAmount: 0,
          remark: item?.remark || '',
        }))
      goodsDialogLoading.value = false
      return
    } catch (error) {
      console.warn(`请求 ${url} 失败，尝试下一个`, error)
    }
  }
  goodsDialogLoading.value = false
  ElMessage.error('无法获取进货单明细，请稍后再试')
}

const confirmStockinSelection = () => {
  if (!selectedStockinRow.value) return
  applyStockinToForm(selectedStockinRow.value)
  goodsReturnDetails.value = []
  selectedGoodsRows.value = []
  stockinDialogVisible.value = false
  if (selectedStockinRow.value) {
    loadStockinGoodsDetail(selectedStockinRow.value.stockinGoodsId)
  }
}

const openGoodsDialog = () => {
  if (isDetailMode.value) return
  if (!goodsReturnsForm.stockinGoodsId) {
    ElMessage.warning('请先选择进货单')
    return
  }
  goodsDialogVisible.value = true
  if (!stockinGoodsDetailList.value.length) {
    loadStockinGoodsDetail(goodsReturnsForm.stockinGoodsId)
  }
}

const handleGoodsSelectionChange = (rows: GoodsReturnDetailRow[]) => {
  selectedGoodsRows.value = rows
}

const findDetailByUid = (uid: string) =>
  goodsReturnDetails.value.find((item) => item.uid === uid)

const confirmGoodsSelection = () => {
  selectedGoodsRows.value.forEach((item) => {
    const exists = goodsReturnDetails.value.find(
      (detail) =>
        detail.productId === item.productId &&
        detail.stockinGoodsDetailId === item.stockinGoodsDetailId,
    )
    if (!exists) {
      goodsReturnDetails.value.push({
        ...item,
        uid: `${item.stockinGoodsDetailId || item.productId}-${Date.now()}`,
        returnQuantity: 0,
        returnAmount: 0,
      })
    }
  })
  goodsDialogVisible.value = false
  selectedGoodsRows.value = []
  updateSummary()
}

const validateDetails = () => {
  if (!goodsReturnDetails.value.length) {
    ElMessage.warning('请添加退货明细')
    return false
  }
  const invalid = goodsReturnDetails.value.find((item) => !item.returnQuantity || item.returnQuantity <= 0)
  if (invalid) {
    ElMessage.warning('请填写所有明细的退货数量')
    return false
  }
  return true
}

const buildSavePayload = () => {
  const details = goodsReturnDetails.value.map((item) => ({
    stockinGoodsDetailId: item.stockinGoodsDetailId,
    productId: item.productId,
    productName: item.productName,
    productCode: item.productCode,
    productTypeName: item.productTypeName,
    specificationModel: item.specification,
    unitName: item.unitName,
    quantity: item.returnQuantity,
    purchasePrice: item.unitPrice,
    amount: item.returnAmount,
    remark: item.remark,
    // 兼容旧字段
    goodsReturnsQuantity: item.returnQuantity,
    goodsReturnsUnitPrice: item.unitPrice,
    goodsReturnsAmount: item.returnAmount,
  }))
  return {
    ...goodsReturnsForm,
    goodsReturnsId: goodsReturnsForm.goodsReturnsId,
    goodsReturnsQuantity: detailSummary.count,
    goodsReturnsAmount: detailSummary.amount,
    goodsReturnsDetails: details,
    goodsDetails: details,
  }
}

const handleSave = async (type: 'normal' | 'new' = 'normal') => {
  if (saving.value) return
  await formRef.value?.validate()
  if (!validateDetails()) return
  saving.value = true
  try {
    const payload = buildSavePayload()
    let res
    if (isEditMode.value) {
      res = await myaxios.put('/api/GoodsReturns/UpdateGoodsReturns', payload)
    } else {
      res = await myaxios.post('/api/GoodsReturns/CreateGoodsReturns', payload)
    }
    if (res?.data?.code === 200) {
      ElMessage.success(res?.data?.message || '保存成功')
      if (type === 'new') {
        handleReset()
        return
      }
      router.push('/getgoodsreturn')
    } else {
      ElMessage.error(res?.data?.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存退货单失败:', error)
    ElMessage.error(error?.response?.data?.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  goodsReturnsForm.goodsReturnsNo = ''
  goodsReturnsForm.goodsReturnsDate = moment().format('YYYY-MM-DD')
  goodsReturnsForm.goodsReturnsAuditor = goodsReturnsForm.goodsReturnsAuditor || ''
  goodsReturnsForm.createrTime = moment().format('YYYY-MM-DD HH:mm:ss')
  goodsReturnsForm.stockinGoodsId = null
  goodsReturnsForm.stockinGoodsNo = ''
  goodsReturnsForm.supplierId = ''
  goodsReturnsForm.supplierName = ''
  goodsReturnsForm.goodsReturnsContact = ''
  goodsReturnsForm.goodsReturnsContactPhone = ''
  goodsReturnsForm.goodsReturnsDepartment = ''
  goodsReturnsForm.goodsReturnsUser = ''
  goodsReturnDetails.value = []
  selectedStockinRow.value = null
  updateSummary()
}

const handleBack = () => {
  router.back()
}

const applyGoodsReturnsDetail = (data: any) => {
  goodsReturnsForm.goodsReturnsId = data.goodsReturnsId || data.GoodsReturnsId
  goodsReturnsForm.goodsReturnsNo = data.goodsReturnsNo || data.GoodsReturnsNo
  goodsReturnsForm.goodsReturnsDate =
    formatDate(data.goodsReturnsDate || data.GoodsReturnsDate) || goodsReturnsForm.goodsReturnsDate
  goodsReturnsForm.stockinGoodsId = data.stockinGoodsId || data.StockinGoodsId
  goodsReturnsForm.stockinGoodsNo = data.stockinGoodsNo || data.StockinGoodsNo || ''
  goodsReturnsForm.supplierId = data.supplierId || data.SupplierId
  goodsReturnsForm.supplierName = data.supplierName || data.SupplierName || ''
  goodsReturnsForm.goodsReturnsContact = data.goodsReturnsContact || data.contactName || ''
  goodsReturnsForm.goodsReturnsContactPhone =
    data.goodsReturnsContactPhone || data.contactPhone || ''
  goodsReturnsForm.goodsReturnsDepartment =
    data.goodsReturnsDepartment || data.organizationName || ''
  goodsReturnsForm.goodsReturnsUser = data.goodsReturnsUser || data.userName || ''
  goodsReturnsForm.goodsReturnsReason = data.goodsReturnsReason || data.reason || ''
  goodsReturnsForm.goodsReturnsRemark = data.goodsReturnsRemark || data.remark || ''
  goodsReturnsForm.goodsReturnsAuditor =
    data.goodsReturnsAuditor || data.auditor || goodsReturnsForm.goodsReturnsAuditor
  goodsReturnsForm.createrTime =
    data.createrTime ||
    data.auditTime ||
    goodsReturnsForm.createrTime ||
    moment().format('YYYY-MM-DD HH:mm:ss')

  const details =
    data.goodsReturnsDetails ||
    data.details ||
    data.GoodsReturnsDetails ||
    data.detailList ||
    []
  goodsReturnDetails.value = details.map((item: any, index: number) => ({
    uid: `${item.goodsReturnsDetailId || item.id || index}`,
    stockinGoodsDetailId: item.stockinGoodsDetailId,
    productId: item.productId,
    productName: item.productName,
    productCode: item.productCode,
    productTypeName: item.productTypeName,
    specification: item.specification,
    unitName: item.unitName,
    stockinQuantity: Number(item.stockinQuantity || 0),
    storedQuantity: Number(item.storedQuantity || 0),
    unstoredQuantity: Number(item.unstoredQuantity ?? item.stockinQuantity ?? 0),
    returnQuantity: Number(item.goodsReturnsQuantity || item.quantity || 0),
    unitPrice: Number(item.goodsReturnsUnitPrice || item.unitPrice || 0),
    returnAmount: Number(item.goodsReturnsAmount || item.amount || 0),
    remark: item.remark,
  }))
  updateSummary()
}

const loadGoodsReturnsDetail = async (id: string) => {
  try {
    const res = await myaxios.get('/api/GoodsReturns/GetGoodsReturnsDetail', {
      params: { goodsReturnsId: id },
    })
    if (res?.data?.code === 200) {
      applyGoodsReturnsDetail(res.data.data || {})
    }
  } catch (error) {
    console.error('获取退货单详情失败:', error)
  }
}

onMounted(async () => {
  await initAuditorInfo()
  if (editingId.value) {
    loadGoodsReturnsDetail(editingId.value)
  }
})
</script>

<style scoped>
.goods-returns-create {
  padding: 16px 16px 96px;
  background: #f5f7fa;
}

.page-header {
  margin-bottom: 16px;
}

.card-section {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  font-size: 16px;
}

.detail-header {
  justify-content: space-between;
}

.detail-actions {
  display: flex;
  gap: 8px;
}

.readonly-input :deep(.el-input__inner) {
  cursor: pointer;
}

.required-label {
  color: #f56c6c;
}

.required-label::before {
  content: '* ';
  color: #f56c6c;
}

.detail-summary {
  margin-top: 12px;
  padding: 12px 16px;
  background: #f9fafc;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  display: flex;
  gap: 24px;
}

.detail-summary strong {
  color: #303133;
  font-weight: 600;
}

.fixed-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  padding: 12px 24px;
  display: flex;
  justify-content: flex-end;
  z-index: 20;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin-bottom: 12px;
}

.dialog-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.goods-dialog-header {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
  font-size: 13px;
  color: #606266;
}
</style>

